<template>
  <div class="main">
    <div class="functionalArea">
      <el-button 
        v-for="item in functionalArea" 
        :key="item.name" 
        @click="showDialog(item.name)"
        size="large" 
        icon="CirclePlus" 
        type="primary">
        {{ item.name }}
      </el-button>
    </div>
    <div class="eventList">
      <div class="statistics">
        <div class="copywritingTitle">共计{{total}}个AI任务</div>
        <!-- <div>
          <el-select v-model="value" class="m-2" placeholder="Select">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button  
            type="primary"
            @click="search(scope.$index, scope.row)"
            >筛选</el-button
          >
        </div> -->
      </div>
      <el-table :data="tableData" stripe  :header-cell-style="{backgroundColor: '#f3f6f9',color:'#333',height:'50px'}" style="width: 100%" >
        <el-table-column prop="TransTime" label="提交任务日期" width="180"/>
        <el-table-column prop="ChatTitle" label="任务类型" width="180" />
        <el-table-column prop="demand" label="AI需求" >
          <template #default="props">
            <div m="4">
              <span m="t-0 b-2" v-show="props.row.demand.product">产品描述: {{ props.row.demand.product }}; </span>
              <span m="t-0 b-2" v-show="props.row.demand.company">公司描述: {{ props.row.demand.company}}; </span>
              <span m="t-0 b-2" v-show="props.row.demand.keyword">关键词: {{ props.row.demand.keyword}}; </span>
              <span m="t-0 b-2" v-show="props.row.demand.paragraphs">写作段落: {{ props.row.demand.paragraphs}}; </span>
              <span m="t-0 b-2" v-show="props.row.demand.modal">写作字数: {{ props.row.demand.modal}}; </span>
              <span m="t-0 b-2" v-show="props.row.demand.language">目标语言: {{ props.row.demand.language}}; </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="" width="220px" fixed="right">
          <template #default="scope">
            <div v-if="scope.row.Status === 0">
              等待AI生成中
            </div>
            <div v-else-if="scope.row.Status === 2">
              <el-icon class="is-loading">
                <Loading />
              </el-icon>
              AI生成中
            </div>
            <div v-else-if="scope.row.Status === 1">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">查看回答</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row.Id, scope.row)">删除</el-button>
            </div>
            <div v-else>
              AI生成失败
            </div>
          </template>
          <!-- <template #default="scope">
            <el-button  
              type="primary"
              plain
              @click="handleEdit(scope.row)"
              >查看回答</el-button
            >
            <el-button
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template> -->
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background layout="prev, pager, next" :total="total" />
      </div>
    </div>
  </div>
  <productIntroduction :name="name" :loading="loading" :dialogVisible="dialogVisible" @closeDialog="closeDialog" @submit="submit"></productIntroduction>
  <answerDialog :answerForm="answerForm" v-model="answerDialog" @closeanswer="closeanswer"></answerDialog>
</template>

<script>
import axios from 'axios'
import { connrequest, getgptchat } from '../api/connrequest'
import { parseTime } from '../utils/index'
import productIntroduction from './components/productIntroduction.vue'
import answerDialog from './components/answerDialog.vue'
export default {
  components:{
    productIntroduction,
    answerDialog
  },
  data(){
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      functionalArea: [
        {name: '文案编写'},
        // {name: '原创博客'},
        // {name: '文章写作'},
        // {name: '新闻采集改写'}
      ],
      value: '所有文案',
      options: [
        { value: '所有文案', label: '所有文案'},
        { value: '文案编写', label: '文案编写'},
        { value: '原创博客', label: '原创博客'},
        { value: '文章写作', label: '文章写作'},
        { value: '新闻采集改写', label: '新闻采集改写'},
      ],
      tableData:[],
      name: '',
      dialogVisible: false,
      loading: false,
      timer: null,
      flag: false,
      answerDialog: false,
      answerForm: {}
    }
  },
  created(){
    this.getData()
  },
  beforeDestroy() {
    if(this.timer) { //如果定时器还在运行 或者直接关闭，不用判断
      clearInterval(this.timer); //关闭
    }
  },
  methods:{
    async getData(){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          Status: 2,
          Name: sessionStorage.getItem('Name')
        }
      }
      const res = await connrequest('GetChatGPTLog', data)
      this.flag = false
      res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        item.demand = this.extractContent(item.Question)
        if(item.Status === 0 || item.Status === 2){
          this.flag = true
        }
      })
      if(this.flag === false){
        window.clearInterval(this.timer);
      }
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    search(){
      this.$message.info('该功能还在开发中')
    },
    handleSizeChange(){},
    handleCurrentChange(num){
      this.pageNum = num
      this.getData()
    },
    extractContent(paragraph) {
      const productRegex = /(?<=product description: {)[^{}]+(?=})/;
      const keywordRegex = /(?<=Combine keywords: {)[^{}]+(?=})/;
      const companyRegex = /(?<=Combining company description: {)[^{}]+(?=})/;
      const paragraphsRegex = /(?<=in )[0-9]+(?= paragraphs\.)/;
      const modalRegex = /(?<=approximately)[^ ]+(?= words of written content)/;
      const wordCountRegex = /\d+(?= words of)/;
      const languageRegex = /(?<=written content in )\w+/;
      const product = paragraph.match(productRegex) ? paragraph.match(productRegex)[0] : '';
      const keyword = paragraph.match(keywordRegex) ? paragraph.match(keywordRegex)[0] : '';
      const company = paragraph.match(companyRegex) ? paragraph.match(companyRegex)[0] : '';
      const paragraphs = paragraph.match(paragraphsRegex) ? parseInt(paragraph.match(paragraphsRegex)[0]) : '';
      const modal = paragraph.match(modalRegex) ? paragraph.match(modalRegex)[0] : '';
      const wordCount = paragraph.match(wordCountRegex) ? parseInt(paragraph.match(wordCountRegex)[0]) : '';
      const language = paragraph.match(languageRegex) ? paragraph.match(languageRegex)[0] : '';
      return {
        product,
        keyword,
        company,
        paragraphs,
        modal,
        wordCount,
        language,
      };
    },
    handleEdit(row){
      let Answer = JSON.parse(row.Answer)?.choices?.[0]?.message?.content || JSON.parse(row.Answer)?.Error?.Msg
      this.answerForm = {product: this.extractContent(row.Question), AIanswer: Answer}
      this.answerDialog = true
    },
    handleDelete(uuid){
      this.$confirm('删除后无法恢复，是否确认删除?', '删除任务', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const data = {
          Data:{
            Id: uuid
          }
        }
        const res = await connrequest('HideChatGPTLog', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });          
      });
    },
    showDialog(name){
      if(name !== '文案编写'){
        this.$message.info('该功能还在开发中')
        return
      }
      this.name = name
      this.dialogVisible = true
    },
    closeDialog(){
      this.dialogVisible = false
    },
    closeanswer(){
      this.answerDialog = false
    },  
    async submit(form){
      this.loading = true
      try {
        const product = form.product;
        const companyDescription = form.company ? `,Combining company description: {${form.company}}` : '';
        const keywords = form.keyword ? `,Combine keywords: {${form.keyword}}` : '';
        const paragraphs = form.paragraphs ? form.paragraphs : '3';
        const writingTone = form.modal ? form.modal : 'formal';
        const wordCount = form.wordCount ? form.wordCount : '500';
        const language = form.language ? form.language : 'English';
        const prompt = `Write a product introduction, combining with product description: {${product}}${companyDescription}${keywords},in ${paragraphs} paragraphs. Use the writing tone of ${writingTone} and output approximately${wordCount} words of written content in ${language}.`;
        this.apiMessage = [{role: 'system', content: 'you are a helpful assistant.'}]
        this.apiMessage.push({role:'user', content: prompt})
        let model = JSON.parse(sessionStorage.getItem('AiMode')).Copywriter
        const Question = {
          // Data: {
            model: model,
            messages: this.apiMessage,
          // }
        }
        const data = {
          Data:{
            Name: sessionStorage.getItem('Name'),
            ChatTitle:"文案编写",
            Question: JSON.stringify(Question),
            Action: 2
          }
        }
        await connrequest('WriteChatGPTLog', data)
        this.getData()
        this.loading = false
        this.dialogVisible = false
        this.timer = window.setInterval(() => {
          this.getData();
        }, 6000);
      } catch (error) {
        this.loading = false
        this.$message.error('发生错误，请重试！')
      }
    },
  }
}
</script>

<style lang="scss" scoped>
  .main{
    width: calc(100vw - 125px);
    height: calc(100vh - 60px);
    background: #fff;
    padding: 20px;
    margin: 10px;
    .functionalArea{
      margin-bottom: 20px;
      .el-button{
        margin-right: 20px;
      }
    }
    .eventList{
      height: calc(100vh - 175px);
      overflow-y: auto;
      border: 1px solid #ebeef5;
      .statistics{
        height: 65px;
        padding: 0 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .el-select{
          margin-right: 10px;
        }
      }
    }
    .pagination{
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
</style>